import api from '../../utils/api.js'

Page({
  data: {
    announcements: [],
    categories: [],
    currentCategory: '',
    loading: true,
    hasMore: true,
    page: 1, // 已经是数字类型
    limit: 10 // 已经是数字类型
  },

  async onLoad() {
    await this.loadCategories()
    await this.loadAnnouncements()
  },

  // 加载分类
  async loadCategories() {
    try {
      const response = await api.announcements.getCategories()
      // 修复：从 response.data 获取分类数据
      this.setData({ categories: response.data || [] })
    } catch (error) {
      console.error('获取分类失败:', error)
    }
  },

  // 加载公告列表
  async loadAnnouncements(reset = true) {
    // 首次加载（reset=true）不要被 loading 拦截；仅在连续触底加载时拦截
    if (this.data.loading && !reset) return
    
    this.setData({ loading: true })
    
    try {
      const params = {
        page: parseInt(this.data.page), // 确保为数字类型
        limit: parseInt(this.data.limit) // 确保为数字类型
      }
      
      if (this.data.currentCategory) {
        params.category = this.data.currentCategory
      }

      const result = await api.announcements.getList(params)
      
      const newAnnouncements = reset ? 
        result.list : 
        [...this.data.announcements, ...result.list]
      
      this.setData({
        announcements: newAnnouncements,
        hasMore: result.pagination.page < result.pagination.pages,
        loading: false
      })
    } catch (error) {
      console.error('获取公告列表失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 分类切换
  async onCategoryChange(e) {
    const category = e.detail.value
    this.setData({ 
      currentCategory: category, 
      page: 1 // 确保重置为数字类型
    })
    await this.loadAnnouncements(true)
  },

  // 点击公告
  onAnnouncementTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/announcements/detail?id=${id}`
    })
  },

  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadAnnouncements()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  async onReachBottom() {
    if (!this.data.hasMore || this.data.loading) return
    
    this.setData({ 
      page: this.data.page + 1 // 数字运算，确保结果为数字
    })
    await this.loadAnnouncements(false)
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '展馆公告 - 南京中医药大学校史馆',
      path: '/pages/announcements/list'
    }
  }
})